<template>
    <ModalCom v-bind="$attrs" width="520px" @open="modalOpen" :inner-loading="innerLoading" :ok-async="okAsync">
      <Form ref="formFieldsRef" :list="state.controlList" :fields="state.fields"></Form>
    </ModalCom>
</template>

<script setup>
import { reactive, ref } from "vue"
// 跨级组件
import ModalCom from "@/components/modal/index.vue"
import Form from "@/components/form/index.vue"
import { message } from "ant-design-vue"
// 校验函数
import { validateRequired } from "@/utils/index"
// api
import { literatureAdd, literatureupdate } from "@/api/index"
// props
const props = defineProps({
  row: {
    type: Object,
    default: () => ({})
  }
})

// formFieldsRef
const formFieldsRef = ref(null)
const state = reactive({
  controlList: [
    { 
      label: "文献名称", 
      field: "literature_name", 
      control: "input", 
      maxlength: 20,
      rules: [validateRequired("请输入文献名称")]
    },
  ],
  fields: {
    literature_name: "",
  }
})

const okAsync = () => {
  return new Promise((resolve, reject) => { // then，catch
    formFieldsRef.value.validataForm().then(() => {
      const id = props.row.literature_id
      // 新增
      if(!id) {
        add().then(() => {
          resolve()
        }).catch(() => {
          reject()
        })
        return
      }
      // 编辑
      edit().then(() => {
        resolve()
      }).catch(() => {
        reject()
      })
      
    }).catch(() => {
      reject()
    })
  })
}

/**
 * 新增
 */
const add = () => {
  return new Promise((resolve, reject) => {
    literatureAdd(state.fields).then((res) => {
      message.success(res.msg)
      resolve()
    }).catch(() => {
      reject()
    })
  })
}

/**
 * 编辑
 */
 const edit = () => {
  return new Promise((resolve, reject) => {
    literatureupdate({
      ...state.fields,
      literature_id: props.row.literature_id
    }).then((res) => {
      message.success(res.msg)
      resolve()
    }).catch(() => {
      reject()
    })
  })
}

const innerLoading = () => {
  return new Promise((resolve, reject) => { // then，catch
    setTimeout(() => {
      resolve()
    }, 500)
  })
}
const modalOpen = () => {
  state.fields.literature_name = props?.row?.literature_name
}
</script>